$(function() {
   $(".form-myt-purchase-purchase-order-bpmReceipt").data("formOptions", {
       bindEvents : function() {
           var $form = $(this);
           $form.find(".btn-delivery-by-amount").click(function() {
               
               $form.data("formOptions").shareRoadAmountToRows.call($form);
           });
          
       },
      updateTotalAmount : function() {
           var $form = $(this);
           var $grid = $form.find(".grid-myt-puchase-order-bpmReceipt");
           var userData = {
               "commodity.display" : "合计："
           };
           // 更新表格汇总统计数据
           userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
           userData.amount = $grid.jqGrid('sumColumn', 'amount');
           userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
           userData['extraAttributes.roadAmount'] = $grid.jqGrid('sumColumn', 'extraAttributes.roadAmount');
           userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');
           userData.costAmount = $grid.jqGrid('sumColumn', 'costAmount');
           $grid.jqGrid("footerData", "set", userData, true);

           $form.setFormDatas({
               amount : userData.amount,
               totalDeliveryAmount : userData.deliveryAmount,
               totalDiscountAmount : userData.discountAmount,
               'extraAttributes.totalRoadAmount' : userData['extraAttributes.roadAmount'],
               'extraAttributes.totalCostAmount' : userData.costAmount
           });
       },
       updateTotalAccountAmount : function() {
           var $form = $(this);
           var $grid = $form.find(".grid-myt-purchase-order-bpmReceipt-accountSubjects");
           var userData = {
               "accountSubject.display" : "合计："
           };

           var ids = $grid.jqGrid("getDataIDs");
           var sum1 = 0;
           var sum2 = 0;
           var sum = 0;
           var supplierId = $form.find("select[name='supplier.id']").val();
           $.each(ids, function(i, id) {
               var rowdata = $grid.jqGrid("getRowData", id);
               var bizTradeUnitId = rowdata['tradeReceipt.bizTradeUnit.id'].split("_")[1];
               if (bizTradeUnitId != supplierId) {
                   if (rowdata['costable'] == 'true') {
                       sum1 = MathUtil.add(sum1, rowdata['amount']);
                   } else {
                       sum2 = MathUtil.add(sum2, rowdata['amount']);
                   }
               } else {
                   rowdata['costable'] = 0;
                   $grid.jqGrid('setRowData', id, rowdata);
               }
               sum = MathUtil.add(sum, rowdata['amount']);
           });
           userData.amount = sum;
           $grid.jqGrid("footerData", "set", userData, true);
           $form.setFormDatas({
               paymentRoadAmount : sum1,
               actualPayedAmount : sum,
               paymentCommodityAmount : sum2
           });
       },
       shareRoadAmountToRows : function() {
           var $form = $(this);
           var $grid = $form.find(".grid-myt-puchase-order-bpmReceipt");
           if ($grid.jqGrid("isEditingMode", true)) {
               return false;
           }
           // 按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
           var totalRoadAmount = $form.find("input[name='paymentRoadAmount']").val();
           var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
           var perRoadAmount = MathUtil.div(totalRoadAmount, totalOriginalAmount, 5);

           var lastrowid = null;
           var tempRoadAmount = 0;
           var ids = $grid.jqGrid("getDataIDs");
           $.each(ids, function(i, id) {
               var rowdata = $grid.jqGrid("getRowData", id);
               if (rowdata['commodity.id'] != '') {
                   rowdata['extraAttributes.roadAmount'] = MathUtil.mul(perRoadAmount, rowdata['originalAmount']);
                   $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'extraAttributes.roadAmount','false');
                   $grid.jqGrid('setRowData', id, rowdata);
                   tempRoadAmount = MathUtil.add(tempRoadAmount, rowdata['roadAmount']);
                   lastrowid = id;
               }
           });

           // 最后一条记录需要以减法计算以修正小数精度问题
           if (lastrowid) {
               var rowdata = $grid.jqGrid("getRowData", lastrowid);
               rowdata['roadAmount'] = MathUtil.sub(totalRoadAmount, MathUtil.sub(tempRoadAmount,
                       rowdata['roadAmount']));
               $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'roadAmount','false');
               $grid.jqGrid('setRowData', lastrowid, rowdata);
           }

           $form.data("formOptions").updateTotalAmount.call($form);
       },
       preValidate : function() {
           var $form = $(this);
           $form.data("formOptions").shareRoadAmountToRows.call($form);
       }
       
 });
   $(".grid-myt-puchase-order-bpmReceipt").data("gridOptions", {
       calcRowAmount : function(rowdata, src,isCalOriginalData) {
         //是否计算原始信息：单价 折扣等
           if(isCalOriginalData!='false'){
               rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
               if (src == 'discountAmount') {
                   rowdata['discountRate'] = MathUtil.mul(MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'],
                           5), 100);
                   rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
               } else if (src == 'amount') {

                   rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                   rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
               } else {

                   rowdata['discountAmount'] = MathUtil.div(
                           MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                   rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
               }
           }
          
           // 先计算金额，在计算单价，以避免精度问题
           rowdata['costAmount'] = MathUtil.add(MathUtil.add(rowdata['amount'], rowdata['deliveryAmount']),
                   rowdata['extraAttributes.roadAmount']);
           rowdata['costPrice'] = MathUtil.div(rowdata['costAmount'], rowdata['quantity']);

       },
       updateRowAmount : function(src) {

           var $grid = $(this);
           var rowdata = $grid.jqGrid("getEditingRowdata");
           $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
           $grid.jqGrid("setEditingRowdata", rowdata);

       },
       batchEntitiesPrefix : "purchaseOrderDetails",
       url : function() {
           var pk = $(this).attr("data-pk");
           if (pk) {
               return WEB_ROOT + "/myt/purchase/purchase-order!purchaseOrderDetails?id=" + pk ;
           }
       },
       colModel : [  {
           label : '所属订单主键',
           name : 'purchaseOrder.id',
           editable:true,
           hidden : true,
           hidedlg : true,
           formatter : function(cellValue, options, rowdata, action) {
               var pk = $(this).attr("data-pk");
               return pk ? pk : "";
           }
       }, {
           label : '商品主键',
           name : 'commodity.id',
           editable:true,
           hidden : true,
           hidedlg : true
       }, {
           name : 'commodity.sku',
           hidden : true,
           hidedlg : true,
           editable : true
       }, {
           label : '行项号',
           name : 'subVoucher',
           width : 50,
           editable : true,
           editrules : {
               required : true
           },
           editoptions : {
               dataInit : function(elem) {
                   var $el = $(elem);
                   if ($el.val() == '') {
                       var $jqgrow = $el.closest(".jqgrow");
                       var idx = $jqgrow.parent().find(".jqgrow:visible").index($jqgrow);
                       $el.val(100 + idx * 10);
                   }
               }
           },
           align : 'center'
       }, {
           label : '采购商品',
           name : 'commodity.display',
           editable : true,
           editoptions : {
               placeholder : '输入商品信息提示选取或双击选取',
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   // 弹出框的选取回调函数
                   var selectCommodity = function(item) {
                       
                       var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                       
                       var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                       var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                       for(i=0; i<ids.length; i++){
                           var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                           if(item['sku'] == row['commodity.sku']){
                               // SKU一致即认为是同一商品
                               existRowId = ids[i];
                               oldQuantity = row.quantity;
                               break;
                           }
                       }
                       
                       if(existRowId){
                           $grid.jqGrid("setRowData", existRowId, {
                               'quantity' : Number(oldQuantity)+1
                           });
                           var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                           $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                           $grid.jqGrid("setRowData", existRowId, myrowdata);
                       }else{
                           var myrowdata = {
                                   'commodity.sku' : item['sku'],//商品唯一性标识
                                   'commodity.id' : item.id,
                                   'commodity.barcode' : item.barcode,
                                   'price' : item.price,
                                   'measureUnit' : item.measureUnit,
                                   'commodity.display' : item.title,
                                   'storageLocation.id' : item['defaultStorageLocation.id'],
                                   'quantity' : 1,
                                   'discountRate' : 0,
                                   'deliveryAmount' : 0
                           };
                           $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                           existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                       }
                       
                       // 整个Form相关金额字段更新
                       var $form = $grid.closest("form");
                       $form.data("formOptions").updateTotalAmount.call($form);
                       
                       // 计算并设置行项号
                       var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                       $grid.jqGrid('setRowData', existRowId, {
                           subVoucher : 100 + idx * 10
                       });
                   }
                   // 自动完成框的选取回调函数
                   var autocompleteSelectCommodity = function(item) {
                       
                       var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                       
                       var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                       for(i=0; i<ids.length; i++){
                           var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                           if(item['sku'] == row['commodity.sku']){
                               // SKU一致即认为是同一商品
                               existRowId = ids[i];
                               break;
                           }
                       }
                       
                       if(existRowId){
                           var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                           alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                           return;
                       }else{
                           var myrowdata = {
                                   'commodity.sku' : item['sku'],//商品唯一性标识
                                   'commodity.id' : item.id,
                                   'commodity.barcode' : item.barcode,
                                   'price' : item.price,
                                   'measureUnit' : item.measureUnit,
                                   'commodity.display' : item.title,
                                   'storageLocation.id' : item['defaultStorageLocation.id'],
                                   'quantity' : 1,
                                   'discountRate' : 0,
                                   'deliveryAmount' : 0
                           };
                           $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                           existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                       }
                       
                       // 整个Form相关金额字段更新
                       var $form = $grid.closest("form");
                       $form.data("formOptions").updateTotalAmount.call($form);
                   }
                   $elem.dblclick(function() {
                       var rowdata = $grid.jqGrid("getEditingRowdata");
                       $(this).popupDialog({
                           url : WEB_ROOT + '/myt/md/commodity!forward?_to_=selectionMore',
                           title : '选取库存商品',
                           callback : function(item) {
                               selectCommodity(item);
                           }
                       })
                       // 多选模式双击弹出选取框之后，取消当前行编辑状态
                       $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                   }).autocomplete({
                       autoFocus : true,
                       source : function(request, response) {
                           var data = Biz.queryCacheCommodityDatas(request.term);
                           return response(data);
                       },
                       minLength : 2,
                       select : function(event, ui) {
                           var item = ui.item;
                           this.value = item.display;

                           autocompleteSelectCommodity(item);
                           event.stopPropagation();
                           event.preventDefault();
                           return false;
                       },
                       change : function(event, ui) {
                           if (ui.item == null || ui.item == undefined) {
                               //$elem.val("");
                               $elem.focus();
                           }
                       }
                   }).focus(function() {
                       $elem.select();
                   });
               }
           },
           width : 200,
           editrules : {
               required : true
           },
          align : 'left'
       }, {
           label : '采购仓库',
           name : 'storageLocation.id',
           width : 150,
           editable:true,
           editrules : {
               required : true
           },
           stype : 'select',
           searchoptions : {
               value : Biz.getStockDatas()
           }
       }, {
           label : '单位',
           name : 'measureUnit',
           editable : true,
           width : 80
       }, {
           label : '数量',
           name : 'quantity',
           width : 80,
           formatter : 'number',
           editable : true,
           editrules : {
               required : true,
               number : true
           },
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   if ($elem.val() == "") {
                       $elem.val(1)
                   }
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                   });
               }
           },
           summaryType : 'sum',
           responsive : 'sm'
       }, {
           label : '单价',
           name : 'price',
           width : 80,
           formatter : 'currency',
           editable : true,
           editrules : {
               required : true,
               number : true
           },
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                   });
               }
           },
           responsive : 'sm'
       }, {
           label : '原价金额',
           name : 'originalAmount',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $elem = $(elem);
                   $elem.attr("readonly", true);
               }
           },
           responsive : 'sm'
       },{
           label : '折扣率(%)',
           name : 'discountRate',
           width : 80,
           formatter : 'currency',
           editable : true,
           editrules : {
               number : true
           },
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                   });
               }
           },
           responsive : 'sm'
       }, {
           label : '折扣额',
           name : 'discountAmount',
           width : 80,
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                   });
               }
           },
           align : 'right',
           responsive : 'sm'
       }, {
           label : '折后金额',
           name : 'amount',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                   });
               }
           },
           responsive : 'sm'
       }, {
           label : '商家运费',
           name : 'deliveryAmount',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   if ($elem.val() == "") {
                       $elem.val(0)
                   }
                   var $form = $elem.closest("form");
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid, $elem.closest("tr.jqgrow"));
                   });
               }
           },
           responsive : 'sm'
       }, {
           label : '其他分摊费用',
           name : 'extraAttributes.roadAmount',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $grid = $(this);
                   var $elem = $(elem);
                   if ($elem.val() == "") {
                       $elem.val(0)
                   }
                   var $form = $elem.closest("form");
                   $elem.keyup(function() {
                       $grid.data("gridOptions").updateRowAmount.call($grid);
                   });
               }
           },
           responsive : 'sm'
       }, {
           label : '批次号',
           name : 'extraAttributes.batchNo',
           width : 150,
           editable:true
       }, {
           label : '批次过期日期',
           name : 'extraAttributes.expireDate',
           width : 80,
           sorttype : 'date',
           editable : true
       }, {
           label : '入库成本单价',
           name : 'costPrice',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $elem = $(elem);
                   $elem.attr("readonly", true);
               }
           },
           responsive : 'sm'
       }, {
           label : '入库总成本',
           name : 'costAmount',
           width : 80,
           formatter : 'currency',
           editable : true,
           editoptions : {
               dataInit : function(elem) {
                   var $elem = $(elem);
                   $elem.attr("readonly", true);
               }
           },
           responsive : 'sm'
       }  ],
       gridComplete:function(){
           var $grid = $(this);
           // 整个Form相关金额字段更新
           var $form = $grid.closest("form");
           $form.data("formOptions").updateTotalAmount.call($form);
       },
       footerrow : true,
      /* beforeInlineSaveRow : function(rowid) {
           var $grid = $(this);
           $grid.data("gridOptions").updateRowAmount.call($grid);
       },*/
       afterInlineSaveRow : function(rowid) {
           var $grid = $(this);
           // 整个Form相关金额字段更新
           var $form = $grid.closest("form");
           $form.data("formOptions").updateTotalAmount.call($form);
       },
       afterInlineDeleteRow : function(rowid) {
           var $grid = $(this);
           // 整个Form相关金额字段更新
           var $form = $grid.closest("form");
           $form.data("formOptions").updateTotalAmount.call($form);
       },
       userDataOnFooter : true
   });
   $(".grid-myt-purchase-order-bpmReceipt-accountSubjects").data("gridOptions",{
               calcRowAmount : function(rowdata, src) {
               },
               updateRowAmount : function(src) {
                   var $grid = $(this);
                   var rowdata = $grid.jqGrid("getEditingRowdata");
                   $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
                   $grid.jqGrid("setEditingRowdata", rowdata);
               },
               url : function() {
                   var bizVoucher = $(this).attr("data-externalVoucher");
                   
                   if (bizVoucher) {
                       return WEB_ROOT + "/myt/finance/payment-receipt-detail!findByPage?search['EQ_tradeReceipt.bizVoucher']="
                               + bizVoucher;
                   }
               },
               colModel : [ {
                   label : '业务凭证号',
                   name : 'tradeReceipt.bizVoucher',
                   width : 120
               }, {
                   label : '付款单凭证号',
                   name : 'tradeReceipt.voucher',
                   width : 150
               }, {
                   name : 'tradeReceipt.bizTradeUnit.id',
                   hidden : true,
                   hidedlg : true,
                   editable : true
               }, {
                   label : '往来单位',
                   name : 'tradeReceipt.bizTradeUnit.display',
                   width : 120,
                   align : 'left'
               }, {
                   name : 'accountSubject.id',
                   hidden : true,
                   hidedlg : true,
                   editable : true
               }, {
                   label : '会计科目',
                   name : 'accountSubject.display',
                   width : 120,
                   align : 'left'
               }, {
                   label : '金额',
                   name : 'amount',
                   width : 80,
                   formatter : 'currency',
                   responsive : 'sm'
               }, {
                   label : '分摊',
                   name : 'costable',
                   width : 30,
                   editable : true,
                   editoptions : {
                       defaultValue : 'true'
                   },
                   edittype : 'checkbox'
               }, {
                   label : '关联凭证',
                   name : 'paymentVouchers',
                   width : 100
               }, {
                   label : '付款参考信息',
                   name : 'paymentReference',
                   edittype : 'textarea',
                   width : 150

               }, {
                   label : '摘要',
                   name : 'memo',
                   width : 150
               } ],
               gridComplete:function(){
                   var $grid = $(this);
                   // 整个Form相关金额字段更新
                   var $form = $grid.closest("form");
                   $form.data("formOptions").updateTotalAccountAmount.call($form);
               },
               footerrow : true,
               beforeInlineSaveRow : function(rowid) {
                   var $grid = $(this);
                   $grid.data("gridOptions").updateRowAmount.call($grid);
               },
               afterInlineSaveRow : function(rowid) {
                   var $grid = $(this);
                   // 整个Form相关金额字段更新
                   var $form = $grid.closest("form");
                   $form.data("formOptions").updateTotalAccountAmount.call($form);
               },
               afterInlineDeleteRow : function(rowid) {
                   var $grid = $(this);
                   // 整个Form相关金额字段更新
                   var $form = $grid.closest("form");
                   $form.data("formOptions").updateTotalAccountAmount.call($form);
               },
               userDataOnFooter : true
           });
   
});
